<?php

namespace app\api\model\service;

use think\Model;
class ShopEnsurePay extends Model
{
    // 表名
    protected $name = 'service_shop_ensure_pay';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 商户保证金充值升级
     * @param $uid
     * @return true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function updateShopEnsure($uid,$price)
    {
        EnsureLog::create(['user_id'=>$uid,'money'=>'+'.$price,'type'=>1,'memo'=>'商户充值保证金']);
        $shop = Shop::where(['user_id'=>$uid])->field('id,user_id,ensure_id,ensure_price,ensure_name')->find();
        $list = ShopEnsure::where(['price'=>['<=',$shop['ensure_price']]])->field('id,name,price,accept_nums,service_nums')->order('price asc')->select();

        if($list)
        {
            $sumEnsurePrice = self::where(['user_id'=>$uid,'state'=>1])->sum('price');
            foreach ($list as $value)
            {
                if($sumEnsurePrice>=$value['price'])
                {
                    Shop::where(['user_id'=>$uid])->update(['ensure_id'=>$value['id'],'ensure_name'=>$value['name'],'accept_nums'=>$value['accept_nums'],'service_nums'=>$value['service_nums']]);
                }
            }
        }
        return true;
    }

    public static function reduceShopEnsure($id)
    {
        $shop = Shop::where(['id'=>$id])->field('id,user_id,ensure_id,ensure_price,ensure_name')->find();

        $shopEnsure = ShopEnsure::where(['price'=>['<=',$shop['ensure_price']]])->field('id,name,price,accept_nums,service_nums')->order('price desc')->find();

        if($shop['ensure_price'] == 0 || empty($shopEnsure))
        {
            Shop::where(['id'=>$id])->update(['ensure_name'=>null,'accept_nums'=>ProjectConfig::getProjectConfig('shop_accept_nums'),'service_nums'=>ProjectConfig::getProjectConfig('service_nums')]);
        }else{
            Shop::where(['id'=>$id])->update(['ensure_id'=>$shopEnsure['id'],'ensure_name'=>$shopEnsure['name'],'accept_nums'=>$shopEnsure['accept_nums'],'service_nums'=>$shopEnsure['service_nums']]);
        }
        return true;
    }



}
